package com.soundplus.app.shp04.Activity;

import static android.content.ContentValues.TAG;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;

import com.example.sppmode.Common.AllParam;
import com.example.sppmode.Common.PairedDeviceInfo;
import com.soundplus.app.shp04.Common.DeviceListAdapter;
import com.example.sppmode.Common.PairedDevMgr;
import com.soundplus.app.shp04.DeviceConnectMgr.DevConnMgr;
import com.soundplus.app.shp04.databinding.ActivityDeviceScanBinding;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;

public class SppDeviceScanActivity extends AppCompatActivity {

    private static final int MSGID_GET_CONNECTED_BT_DEVICE = 1;
    private static final int MSGID_UPDATE_DEV_LIST = 2;

    private Context context;
    private ActivityDeviceScanBinding binding;
    private MyHandler myHandler;

    private DeviceListAdapter deviceListAdapter = null;
    private final List<PairedDeviceInfo> scannedDeviceList = new ArrayList<>();

    private BluetoothAdapter bluetoothAdapter = null;
    private DeviceSortComparator deviceSortComparator = null;
    private DevConnMgr devConnMgr;

    private final boolean checkWhiteList = false;
    private final String[] whiteList = new String[]{"SHP04", "SHP004"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        context = this;
        binding = ActivityDeviceScanBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        myHandler = new MyHandler(context, getMainLooper());

        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        deviceSortComparator = new DeviceSortComparator();
        devConnMgr = DevConnMgr.getInstance();

        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter foundFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mReceiver, foundFilter);
        myHandler.sendMessageDelayed(myHandler.obtainMessage(MSGID_GET_CONNECTED_BT_DEVICE), 100);
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mReceiver);
        stopScanLeDevice();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void exitDeviceScan() {
        boolean firstRunning = AllParam.getAppInfo().isFirstRunning();
        if (firstRunning) {
            Intent intent = new Intent(SppDeviceScanActivity.this, MainActivity.class);
            startActivity(intent);
        }

        SppDeviceScanActivity.this.finish();
    }

    private void initView() {
        scannedDeviceList.clear();

        deviceListAdapter = new DeviceListAdapter(context, scannedDeviceList);
        binding.lvScannedDevice.setAdapter(deviceListAdapter);
        binding.lvScannedDevice.setOnItemClickListener((adapterView, view, i, l) -> {
            stopScanLeDevice();
            addPairedDevice(scannedDeviceList.get(i));
            devConnMgr.disconnectDevice();
        });
//重新扫描键，点击事件
        binding.btnRescan.setOnClickListener(view -> {
            scannedDeviceList.clear();
            deviceListAdapter.notifyDataSetChanged();
            myHandler.sendMessageDelayed(myHandler.obtainMessage(MSGID_GET_CONNECTED_BT_DEVICE), 100);
        });
    }

    private class MyHandler extends Handler {
        Context context;
        Looper looper;

        public MyHandler(Context context, Looper looper) {
            super(looper);
            this.context = context;
            this.looper = looper;
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSGID_GET_CONNECTED_BT_DEVICE:
                    stopScanLeDevice();
                    startScanDevice();
                    break;

                case MSGID_UPDATE_DEV_LIST:
                    deviceListAdapter.notifyDataSetChanged();
                    break;
            }
        }
    }

    /**
     * 搜索到新设备广播广播接收器
     */
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                Log.d(TAG, "mReceiver ACTION_FOUND");
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                dealScanResult(device);
            }
        }
    };

    @SuppressLint("MissingPermission")
    private void startScanDevice() {
        scannedDeviceList.clear();
        deviceListAdapter.notifyDataSetChanged();
        binding.tvScanPrompt.setVisibility(View.VISIBLE);
        getConnectedBtDevice();
    }

    @SuppressLint("MissingPermission")
    private void stopScanLeDevice() {
        binding.tvScanPrompt.setVisibility(View.INVISIBLE);

    }

    //获取已连接的蓝牙设备
    @SuppressLint("MissingPermission")
    private void getConnectedBtDevice() {
        Class<BluetoothAdapter> bluetoothAdapterClass = BluetoothAdapter.class;//得到BluetoothAdapter的Class对象
        try {
            //得到连接状态的方法
            Method method = bluetoothAdapterClass.getDeclaredMethod("getConnectionState", (Class[]) null);
            //打开权限
            method.setAccessible(true);

            int state = (int) method.invoke(bluetoothAdapter, (Object[]) null);
            if (state == BluetoothAdapter.STATE_CONNECTED) {
                Log.i("BLUETOOTH", "BluetoothAdapter.STATE_CONNECTED");
                Set<BluetoothDevice> devices = bluetoothAdapter.getBondedDevices(); //集合里面包括已绑定的设备和已连接的设备
                Log.i("BLUETOOTH", "devices:" + devices.size());
                for (BluetoothDevice device : devices) {
                    Method isConnectedMethod = BluetoothDevice.class.getDeclaredMethod("isConnected", (Class[]) null);
                    method.setAccessible(true);
                    boolean isConnected = (boolean) isConnectedMethod.invoke(device, (Object[]) null);
                    if (isConnected) { //根据状态来区分是已连接的还是已绑定的，isConnected为true表示是已连接状态。
                        Log.i("BLUETOOTH-dh", "connected:" + device.getName());
                        dealScanResult(device);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SuppressLint("MissingPermission")
    private void dealScanResult(BluetoothDevice device) {
        if (device == null)
            return;

        boolean deviceValid = false;
        boolean deviceExsit = false;
        int deviceType = PairedDeviceInfo.DEVICE_TYPE_COMMON;

        if (deviceValid == false && checkWhiteList) {
            for (String str : whiteList) {
                if (str != null) {
                    if (device.getName().startsWith(str)) {
                        deviceValid = true;
                        deviceType = PairedDeviceInfo.DEVICE_TYPE_COMMON;
                        break;
                    }
                }
            }
        } else {
            if (device.getName() != null) {
                deviceValid = true;
                deviceType = PairedDeviceInfo.DEVICE_TYPE_COMMON;
            }
        }

        if (device.getName() == null) {
            Log.d(TAG, "dealScanResult return name ==  null");
            return;
        }

        if (!deviceValid) {
            Log.d(TAG, "dealScanResult return ivalid device");
            return;
        }

        for (PairedDeviceInfo pairedDeviceInfo : scannedDeviceList) {
            if (pairedDeviceInfo.getMacAddr().equals(device.getAddress())) {
                deviceExsit = true;
                pairedDeviceInfo.setRssi(0);
                break;
            }
        }

        if (!deviceExsit) {
            PairedDeviceInfo pairedDeviceInfo = new PairedDeviceInfo();
            pairedDeviceInfo.setDevType(deviceType);
            if (device.getName() == null)
                pairedDeviceInfo.setName("Unknown");
            else
                pairedDeviceInfo.setName(device.getName());
            pairedDeviceInfo.setMacAddr(device.getAddress());
            pairedDeviceInfo.setRssi(0);
            scannedDeviceList.add(pairedDeviceInfo);
            Collections.sort(scannedDeviceList, deviceSortComparator);
        }
    }

    private void addPairedDevice(PairedDeviceInfo pairedDeviceInfo) {
        PairedDevMgr pairedDevInfo = AllParam.getPairedDevInfo();
        pairedDevInfo.addDevice(pairedDeviceInfo);
        pairedDevInfo.updateLastConnDevInfo(pairedDeviceInfo, true);
        exitDeviceScan();
    }

    class DeviceSortComparator implements Comparator {

        @Override
        public int compare(Object object1, Object object2) {
            PairedDeviceInfo pairedDeviceInfo1 = (PairedDeviceInfo) object1;
            PairedDeviceInfo pairedDeviceInfo2 = (PairedDeviceInfo) object2;
            int rssi1 = pairedDeviceInfo1.getRssi();
            int rssi2 = pairedDeviceInfo2.getRssi();

            if (rssi1 < rssi2)
                return 1;
            else if (rssi1 > rssi2)
                return -1;
            return 0;
        }
    }

}
